"""
模板管理API端点
提供模板相关的API接口，包括模板查询、应用和管理功能。
"""

import logging
from fastapi import APIRouter, HTTPException, Query
from typing import Dict, Any, Optional, List
from pydantic import BaseModel

from ..services.template_manager import template_manager
from ..models.template_config import TemplateConfig

logger = logging.getLogger(__name__)

router = APIRouter()


class TemplateApplyRequest(BaseModel):
    """模板应用请求模型"""
    template_id: str
    slide_type: str = "content_slide"
    content: Dict[str, Any]


class TemplateCreateRequest(BaseModel):
    """模板创建请求模型"""
    template_config: Dict[str, Any]


@router.get("/templates")
async def get_all_templates(
    category: Optional[str] = Query(None, description="按分类筛选"),
    active_only: bool = Query(True, description="仅返回激活的模板")
):
    """
    获取所有模板列表
    
    Args:
        category: 模板分类筛选
        active_only: 是否仅返回激活的模板
        
    Returns:
        Dict: 模板列表
    """
    try:
        if category:
            templates = template_manager.get_templates_by_category(category)
        elif active_only:
            templates = template_manager.get_active_templates()
        else:
            templates = template_manager.get_all_templates()
        
        # 转换为预览格式
        template_previews = {}
        for template_id, template_config in templates.items():
            template_previews[template_id] = template_manager.get_template_preview(template_id)
        
        return {
            "success": True,
            "message": f"获取模板列表成功，共 {len(template_previews)} 个模板",
            "templates": template_previews,
            "total_count": len(template_previews)
        }
        
    except Exception as e:
        logger.error(f"获取模板列表失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"获取模板列表失败: {str(e)}"
        )


@router.get("/templates/{template_id}")
async def get_template_detail(template_id: str):
    """
    获取指定模板的详细配置
    
    Args:
        template_id: 模板ID
        
    Returns:
        Dict: 模板详细配置
    """
    try:
        template_config = template_manager.get_template(template_id)
        
        if not template_config:
            raise HTTPException(
                status_code=404,
                detail=f"模板不存在: {template_id}"
            )
        
        return {
            "success": True,
            "message": "获取模板详情成功",
            "template": template_config.dict()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取模板详情失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"获取模板详情失败: {str(e)}"
        )


@router.get("/templates/{template_id}/preview")
async def get_template_preview(template_id: str):
    """
    获取模板预览信息
    
    Args:
        template_id: 模板ID
        
    Returns:
        Dict: 模板预览信息
    """
    try:
        preview = template_manager.get_template_preview(template_id)
        
        if not preview:
            raise HTTPException(
                status_code=404,
                detail=f"模板不存在: {template_id}"
            )
        
        return {
            "success": True,
            "message": "获取模板预览成功",
            "preview": preview
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取模板预览失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"获取模板预览失败: {str(e)}"
        )


@router.post("/templates/apply")
async def apply_template_to_slide(request: TemplateApplyRequest):
    """
    将模板应用到幻灯片
    
    Args:
        request: 模板应用请求
        
    Returns:
        Dict: 应用模板后的幻灯片配置
    """
    try:
        # 验证模板是否存在
        template_config = template_manager.get_template(request.template_id)
        if not template_config:
            raise HTTPException(
                status_code=404,
                detail=f"模板不存在: {request.template_id}"
            )
        
        # 应用模板
        styled_content = template_manager.apply_template_to_slide(
            template_id=request.template_id,
            slide_type=request.slide_type,
            content=request.content
        )
        
        return {
            "success": True,
            "message": "模板应用成功",
            "styled_content": styled_content,
            "template_id": request.template_id,
            "slide_type": request.slide_type
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"应用模板失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"应用模板失败: {str(e)}"
        )


@router.get("/templates/categories")
async def get_template_categories():
    """
    获取所有模板分类
    
    Returns:
        Dict: 模板分类列表
    """
    try:
        templates = template_manager.get_all_templates()
        categories = set()
        
        for template_config in templates.values():
            categories.add(template_config.metadata.category)
        
        categories_list = sorted(list(categories))
        
        return {
            "success": True,
            "message": "获取模板分类成功",
            "categories": categories_list,
            "total_count": len(categories_list)
        }
        
    except Exception as e:
        logger.error(f"获取模板分类失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"获取模板分类失败: {str(e)}"
        )


@router.get("/templates/tags")
async def get_template_tags():
    """
    获取所有模板标签
    
    Returns:
        Dict: 模板标签列表
    """
    try:
        templates = template_manager.get_all_templates()
        all_tags = set()
        
        for template_config in templates.values():
            all_tags.update(template_config.metadata.tags)
        
        tags_list = sorted(list(all_tags))
        
        return {
            "success": True,
            "message": "获取模板标签成功",
            "tags": tags_list,
            "total_count": len(tags_list)
        }
        
    except Exception as e:
        logger.error(f"获取模板标签失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"获取模板标签失败: {str(e)}"
        )


@router.post("/templates")
async def create_template(request: TemplateCreateRequest):
    """
    创建新模板
    
    Args:
        request: 模板创建请求
        
    Returns:
        Dict: 创建结果
    """
    try:
        # 验证模板配置
        template_config = TemplateConfig(**request.template_config)
        
        # 检查模板ID是否已存在
        existing_template = template_manager.get_template(template_config.metadata.id)
        if existing_template:
            raise HTTPException(
                status_code=400,
                detail=f"模板ID已存在: {template_config.metadata.id}"
            )
        
        # 保存模板
        success = template_manager.save_template(template_config)
        
        if success:
            return {
                "success": True,
                "message": "模板创建成功",
                "template_id": template_config.metadata.id
            }
        else:
            raise HTTPException(
                status_code=500,
                detail="模板保存失败"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建模板失败: {e}")
        raise HTTPException(
            status_code=400,
            detail=f"创建模板失败: {str(e)}"
        )


@router.put("/templates/{template_id}")
async def update_template(template_id: str, request: TemplateCreateRequest):
    """
    更新模板配置
    
    Args:
        template_id: 模板ID
        request: 模板更新请求
        
    Returns:
        Dict: 更新结果
    """
    try:
        # 验证模板是否存在
        existing_template = template_manager.get_template(template_id)
        if not existing_template:
            raise HTTPException(
                status_code=404,
                detail=f"模板不存在: {template_id}"
            )
        
        # 验证新的模板配置
        template_config = TemplateConfig(**request.template_config)
        
        # 确保模板ID一致
        if template_config.metadata.id != template_id:
            raise HTTPException(
                status_code=400,
                detail="模板ID不匹配"
            )
        
        # 保存更新后的模板
        success = template_manager.save_template(template_config)
        
        if success:
            return {
                "success": True,
                "message": "模板更新成功",
                "template_id": template_id
            }
        else:
            raise HTTPException(
                status_code=500,
                detail="模板保存失败"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新模板失败: {e}")
        raise HTTPException(
            status_code=400,
            detail=f"更新模板失败: {str(e)}"
        )


@router.delete("/templates/{template_id}")
async def delete_template(template_id: str):
    """
    删除模板
    
    Args:
        template_id: 模板ID
        
    Returns:
        Dict: 删除结果
    """
    try:
        # 验证模板是否存在
        existing_template = template_manager.get_template(template_id)
        if not existing_template:
            raise HTTPException(
                status_code=404,
                detail=f"模板不存在: {template_id}"
            )
        
        # 删除模板
        success = template_manager.delete_template(template_id)
        
        if success:
            return {
                "success": True,
                "message": "模板删除成功",
                "template_id": template_id
            }
        else:
            raise HTTPException(
                status_code=400,
                detail="无法删除该模板（可能是默认模板）"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除模板失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"删除模板失败: {str(e)}"
        )


@router.post("/templates/reload")
async def reload_templates():
    """
    重新加载所有模板
    
    Returns:
        Dict: 重新加载结果
    """
    try:
        template_manager.reload_templates()
        
        templates = template_manager.get_all_templates()
        
        return {
            "success": True,
            "message": "模板重新加载成功",
            "total_templates": len(templates)
        }
        
    except Exception as e:
        logger.error(f"重新加载模板失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"重新加载模板失败: {str(e)}"
        )